$(document).ready(function() {
	//针对新增和修改mail时的dormitory文本框检查
	$("#dormitory").blur(dormitoryBlur);
	//学生姓名框失去焦点时,隐藏studentList
	$("#student").blur(function() {
		var studentList = $("#studentList");
		var lightIndex = studentList.data("lightIndex");
		if (lightIndex != -1) {
			$(this).val(studentList.find("tr:eq(" + (lightIndex - 1) + ")").text());
		}
		$("#studentList").hide();
		//这个地方要注意的是如果隐藏的太快，就不会触发click事件了，文本也不会填到student上面
		
	});
	$(".filterForm select").change(function() {
		var selectedIndex = this.selectedIndex;
		var optionValue = new String(this.options[selectedIndex].value);
		if (optionValue.toLowerCase() == "building") {
			$(".filterForm .dormitoryInput").hide();
			$(".filterForm :submit[name='submit']").removeAttr("disabled");
		} else if (optionValue.toLowerCase() == "dormitory") {
			$(".filterForm .dormitoryInput").show();
			$("#dormitory").next().text("");
			$(".filterForm :submit[name='submit']").attr("disabled", "disabled");
		}		
	});
	//针对过滤框的寝室名检查
	$(".filterForm :text[name='dormitory']").blur(function() {
		$(this).next().text("");
		var buildingId = $(":hidden[name='buildingId']").val();
		var dormitoryName = $(this).val();	
		if (dormitoryName != "") {
			var existed = checkDormitoryExist(buildingId, dormitoryName);
			if (!existed) {
				$(this).next().text("该寝室不存在");
				$(".filterForm :submit").attr("disabled", "disabled");
			} else {
				$(".filterForm :submit[name='submit']").removeAttr("disabled");
			}
		} else {
			$(".filterForm :submit").attr("disabled", "disabled");
		}
	}).focus(function() {
		$("#dormitoryName").next().text("");
	});
		
	$("#mailList :checkbox[name='selectAll']").click(function() {		
		if (!$(this).attr("checked")) {
			$("#mailList :checkbox[name='mailId']").removeAttr("checked");
		} else {
			$("#mailList :checkbox[name='mailId']").attr("checked", "checked");
		}
	});
	
	$(".mailTool :button[name='delete']").click(function() {
		var mailIds = new Array();
		$("#mailList :checkbox[name='mailId']").each(function() {
			if ($(this).attr("checked")) {
				mailIds.push($(this).attr("value"));
			}
		});
		
		if (mailIds.length == 0) {
			$(".ajaxMessage").text("没有选中任何邮件...").show();
			hideAjaxMessage(2000);
		} else {
			var isConfirmed = confirm("你真的要删除吗?");
			if (isConfirmed) {
				var deleteStatus = deleteMails(mailIds);
				if (deleteStatus) {
					for (var i = 0; i < mailIds.length; ++i) {
						var exp = "#mailList tr :checkbox[value='" + mailIds[i] + "']";				
						$(exp).parent().parent().remove();
					}
				}
			} 
		}
	});
	
	//初始化modifyDialog
	$(".modifyDialog").dialog({
		modal : true,
		minWidth : 365,
		minHeight : 410,
		autoOpen : false,
		buttons : {
			"取消" : function() {
				$(this).dialog("close");
			},
			"修改" : modifyMail
		}
	});
	
	$("#mailList :button[name='modify']").click(function() {	
		var modifyDialog = $(".modifyDialog");
		modifyDialog.dialog("open");
		
		var row = $(this).parent().parent();
		var mailId = row.find(":checkbox").val();
		var dormitory = row.children("td[title='dormitory']").text();
		var student = row.children("td[title='student']").text();
		var description = row.children("td[title='description']").text();
		
		modifyDialog.find("input:hidden[name='mailId']").val(mailId);
		modifyDialog.find(":text[name='dormitory']").val(dormitory);
		modifyDialog.find(":text[name='student']").val(student);
		modifyDialog.find("textarea[name='description']").val(description);
		
		modifyDialog.data("modifyRow", row);
	});
	
	$(".datePicker").datepicker({
		changeYear : true,
		dateFormat : "yy-mm-dd"
	});
});

function dormitoryBlur() {
	$(this).next().text("");
	var buildingId = $(":hidden[name='buildingId']").val();
	var dormitoryName = $("#dormitory").val();	
	if (dormitoryName != "") {
		$("#studentList").hide();
		var existed = checkDormitoryExist(buildingId, dormitoryName);		
		if (existed) {			
			getStudentList(buildingId, dormitoryName);
			$("#student").focus();
		} else {			
			$("#dormitoryName,#dormitory").next().text("没有这个寝室！");
			$("form[name='mailDTO'] :submit[name='submit']").attr("disabled", "disabled");
		}
	}
}

function getStudentList(buildingId, dormitoryName) {
	
	$.ajax({
		async : true,
		type : "get",
		data : {
			"building" : buildingId,
			"dormitoryName" : dormitoryName
		},
		dataType : "json",
		url : "../../../ajax/getStudentListByDormitory.do",
		success : function(dormitory, textStatus) {
			var studentList = $("#studentList");
			var students = dormitory.students;
			$(".ajaxMessage").text("获取寝室学生名单...");
			studentList.find("table")
					   .html("");	
			for (i = 0; i < students.length; ++i) {
				studentList.find("table").append("<tr line='" + (i + 1) + "'><td>" + students[i] + "</td></tr>");
			}
			
			studentList.find("table")
					   .append("<tr><td><a name='close' href='#'>关闭</a></td></tr");
			studentList.find("a[name='close']").click(function() {
				studentList.hide();
			});
			studentList.show();
			//激活学生姓名列表，使其可以选择
			activateStudentList(studentList);
		},
		error : function() {
			$(".ajaxMessage").text("请求失败...");
		}
	});
	
}

function activateStudentList(studentList) {
	studentList.data("lightIndex", -1);
	studentList.find("tr")
	  .mouseover(function() {
		studentList.data("lightIndex", $(this).attr("line"));
		$(this).addClass("hover");
	}).mouseout(function() {
		studentList.data("lightIndex", -1);
		$(this).removeClass("hover");
	});//.click(function() {//	$("#student").val($(this).text());studentList.hide();});
	studentList.find("table tr:last-child").unbind("click").unbind("mouseover").mouseover(function() {
		studentList.data("lightIndex", -1);
	});
	
}
/*删除邮件 */
function deleteMails(mailIdArray) {
	var deleteStatus = new Boolean(false);
	$.ajax({
		type : "POST",
		async : true,
		data : {mailIds : mailIdArray},
		dataType : "json",
		url : "deleteMails.do",
		success : function(jsonData, textStatus) {
			if (jsonData.status) {
				deleteStatus = new Boolean(true);
				$(".ajaxMessage").text("删除成功...").show();
			} else {
				deleteStatus = new Boolean(false);
				$(".ajaxMessage").text("删除失败，原因可能是:" + jsonData.message).show();
			}					
		},
		error : function() {
			deleteStatus = new Boolean(false);
			$(".ajaxMessage").text("请求失败,请稍后再试...").show();
		}
	});
	hideAjaxMessage(2000);
	return deleteStatus;
}

function modifyMail() {
	var mailId = $(this).find("input:hidden[name='mailId']").val();
	var dormitoryName = $(this).find(":text[name='dormitory']").val();
	var studentName = $(this).find(":text[name='student']").val();
	var description = $(this).find("textarea[name='description']").val();
	
	$.ajax({
		type : "GET",
		aysnc : true,
		data : {
			"id" : mailId,
			"dormitory" : dormitoryName,
			"student" : studentName,
			"description" : description
		},
		dataType : "json",
		url : "updateMail.do",
		success : function(jsonData, textStatus) {
			if (jsonData.status) {
				var modifyRow = $(".modifyDialog").data("modifyRow");				
				modifyRow.children("td[title='dormitory']").text(dormitoryName);
				modifyRow.children("td[title='student']").text(studentName);
				modifyRow.children("td[title='description']").text(description);
				$(".ajaxMessage").text("更新成功...").show();
			} else {
				$(".ajaxMessage").text("更新失败，原因可能是：" + jsonData.message).show();
			}
			
		},
		error : function() {
			$(".ajaxMessage").text("请求失败,请稍后再试...").show();
		}
	});
	$(this).dialog("close");
	
}

function hideAjaxMessage(time) {
	if (!(time instanceof Number)) {
		time = 2000;
	}
	
	setTimeout(function() {$(".ajaxMessage").hide();}, time);
}
